package com.zhku.laosiji.controller;

import com.zhku.laosiji.pojo.Notice;
import com.zhku.laosiji.service.NoticeService;
import com.zhku.laosiji.utils.ResultUtils;
import com.zhku.laosiji.utils.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by LINWENHAO on 2018/9/11.
 */
@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    @RequestMapping("/list")
    public ModelAndView getList(@RequestParam(name = "keyword",defaultValue = "") String keyword,
                                Map map) {
        List<Notice> notices = noticeService.findALl(keyword);
            map.put("notices", notices);

        return new ModelAndView("feedback-list", map);
    }

    /**
     * 删除
     * @param nid
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public ResultVO delete(@RequestParam("nid") Integer nid){
        try {
            noticeService.delete(nid);

        }catch (Exception e){
            ResultUtils.error(1, e.getMessage());
        }

        return ResultUtils.success();
    }

    /**
     * 添加
     * @param map
     * @return
     */
    @RequestMapping("/add")
    public ModelAndView add(Map map) {
        Notice notice = new Notice();
        map.put("notice", notice);

        return new ModelAndView("feedback-add",map);
    }

    /**
     * 修改
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/edit")
    public ModelAndView edit(@RequestParam("id") Integer id
                            ,Map map) {
        Notice notice = noticeService.findById(id);
        map.put("notice", notice);

        return new ModelAndView("feedback-add",map);
    }

    /**
     * 保存
     * @param notice
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public ResultVO save(Notice notice) {
        //判断是增加还是修改
        if (notice.getId() == null) {
            notice.setAdminId(1);
            notice.setAdminName("admin");
            notice.setCreatedate(new Date());
            noticeService.saveNotice(notice);
        }else {
            Notice oldnotice = noticeService.findById(notice.getId());
            oldnotice.setTitle(notice.getTitle());
            oldnotice.setContent(notice.getContent());
            noticeService.updateNotice(oldnotice);
        }

        return ResultUtils.success();
    }

    @GetMapping("/preview")
    public String previewNotice(@RequestParam("id") Integer id, Model model) {
        Notice notice = noticeService.findById(id);
        model.addAttribute("notice", notice);

        return "user/notice/noticePreview";
    }
}
